package cn.com.maven.designpattern.singleton;

/**
 * 懒汉模式，instance为null时创建新对象,才有双重检查锁，优化了LazySingletonSafe性能
 * @Author YongQiang
 * @Date 2021/5/18 10:37
 * @Version 1.0
 */
public class LazySingletonDoubleCheck {
    private static LazySingletonDoubleCheck instance = null;

    private LazySingletonDoubleCheck(){

    }

    public static LazySingletonDoubleCheck getInstance(){
        if (instance == null) {
            synchronized (LazySingletonDoubleCheck.class){
                if (instance == null){
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    instance = new LazySingletonDoubleCheck();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> System.out.println(LazySingletonDoubleCheck.getInstance())).start();
        }
    }
}
